import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import config from "@/utils/config";
import { message } from "ant-design-vue";
import { getStorageUserInfo, utilLogout } from "@/utils";

axios.defaults.baseURL = config.baseURL
axios.defaults.timeout = 30000
console.log('当前请求地址：', axios.defaults.baseURL)

const service = axios.create()
// Request interceptors
service.interceptors.request.use(
    config => {

        const userInfo = getStorageUserInfo()
        // Add X-Access-Token header to every request, you can add other custom headers here
        if (userInfo && userInfo.token) {
            config.headers['token'] = userInfo.token
        }
        return config
    },
    error => {
        Promise.reject(error)
    }
)
/**
 *
 * @param {*} params
 * @param {*} callback
 * @returns
 */
export const request = async <T = any>(params: AxiosRequestConfig, callback?: (res?: AxiosResponse<T>) => void): Promise<T> => {
    return new Promise((resolve, reject) => {
        service
            .request<T>(params)
            .then(res => {
                const { data } = res as any
                if (res.status !== 200) {
                    if (callback) {
                        callback(res)
                        return
                    }
                    message.error(data.msg)
                    reject(new Error(data.msg || 'Error'))
                } else {
                    const data = res.data as any
                    if (callback) {
                        callback(res)
                        return
                    }
                    if (data.code !== 200) {
                        message.error(data.msg)
                        reject(new Error(data.msg || 'Error'))
                        if (data.code === 105) {
                            utilLogout()
                        }
                        return
                    }
                    resolve(res.data)
                }
            }).catch(err => {
                message.error(err.toString())
                reject({ message: err.toString() })
            })
    })
}
